package com.aisino.encrypt.algorithm;

import com.aisino.encrypt.entity.Digest;
import com.aisino.encrypt.exception.AisinoException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 非对称加密
 *
 * @author 蒋帆
 * @datetime 2021-8-23
 * @description
 * 采用MD5/SHA1加密解密
 */
public class DigestEncrypt {


    /**
     * 编码值
     */
    private static final int INTEGER_CODE = 0xff;

    /**
     *
     */
    private static final int VAL = 16;

    /***
     * MD5和SHA加密 生成32位md5码
     * @param content 需要加密的内容
     * @param digest 加密类型（MD5/SHA）
     * @return 密文
     */
    public static String encrypt(String content, Digest digest) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(digest.getAlgorithm());
        } catch (NoSuchAlgorithmException e) {
            throw new AisinoException(e);
        }
        char[] charArray = content.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] bytes = messageDigest.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (byte byt:bytes
             ) {
            int val = ((int) byt) & INTEGER_CODE;
            if (val < VAL) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();

    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     *
     * @param content 需要加密的内容
     * @return 加密/解密内容
     */
    public static String convert(String content) {
        String s = "";
        char[] a = content.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        s = new String(a);
        return s;

    }

    /**
     * 判断输入数据是否和加密数据相等
     *
     * @param content    输入数据
     * @param ciphertext 加密数据
     * @param digest     摘要加密算法
     * @return true/false
     */
    public static boolean match(String content, String ciphertext, Digest digest) {
        return ciphertext.equals(encrypt(content, digest));
    }

    /**
     * MD5/SHA解密
     *
     * @param ciphertext 需要解密的内容
     * @return 解密后的内容
     */
    public static String decrypt(String ciphertext) {
        return convert(convert(ciphertext));
    }

}
